<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Support\Facades\Redis;


class AuthMobile
{
    const TOKEN =  "ymdIlovemoney20178888";

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {

//        if ($this->auth->guard($guard)->guest()) {
//            return response('Unauthorized.', 401);
//        }
        //@todo token校验

        //仅供修改微信mp后台服务器配置校验使用
        //$this->valid();

        //wx授权获取用户openid

        $token = trim($request->get('token'));
        $info = Redis::get($token);
        if(!$info){
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }

    private function valid()
    {
        if($this->checkSignature()){
            $echoStr = $_GET["echostr"];

            //valid signature , option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself


        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = self::TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}
